package com.lifeonwalden.game.mindustry.processor;

import com.lifeonwalden.game.mindustry.Global;
import com.lifeonwalden.game.mindustry.constant.League;
import com.lifeonwalden.game.mindustry.entity.Surface;
import com.lifeonwalden.game.mindustry.world.Coordinate;
import com.lifeonwalden.game.mindustry.world.Point;

import java.util.Optional;

public class Scanner {
    private League target;

    private float radius;

    public Scanner(League target, float radius) {
        this.radius = radius;
        this.target = target;
    }

    public Optional<Surface> scan(Coordinate center) {
        Point point;
        double power2OfRadius = radius * radius;
        short xOffset;
        short endY = (short) (center.y - radius);
        for (short y = (short) (center.y + radius); y >= endY; y--) {
            xOffset = (short) Math.sqrt(power2OfRadius - Math.pow(Math.abs(y - center.y), 2));

            for (short x = 0; x <= xOffset; x++) {
                if (center.x - x >= 0) {
                    point = Global.world.points[center.x - x][y];
                    if (null != point.obstruction && point.obstruction.league == this.target) {
                        return Optional.of(point.obstruction);
                    } else if (null != point.surface && point.surface.league == this.target) {
                        return Optional.of(point.surface);
                    }
                }
                point = Global.world.points[center.x + x][y];
                if (null != point.obstruction && point.obstruction.league == this.target) {
                    return Optional.of(point.obstruction);
                } else if (null != point.surface && point.surface.league == this.target) {
                    return Optional.of(point.surface);
                }
            }
        }

        return Optional.empty();
    }
}
